package rw;

import jdk.nashorn.internal.ir.CallNode;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ReadWriteLock
 * 独占锁（写锁） 一次只能被一个线程占有
 * 共享锁（读锁） 多个线程可以同时占有
 * 读-读  可以共存
 * 读-写  不可以共存
 * 写-写  不可以共存
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
//        MyCacheLock myCacheLock = new MyCacheLock();
//      写入
        for (int i = 1; i <= 5; i++) {
            int temp = i;
            new Thread(() -> {

                myCache.put(temp + "", temp + "");

            },String.valueOf(i)).start();
        }
//      读取
        for (int i = 1; i <= 5; i++) {
            int temp = i;
            new Thread(() -> {

                myCache.get(temp + "");

            },String.valueOf(i)).start();
        }
    }
}

/**
 * 自定义缓存
 * 方法未加锁，导致写的时候被插队
 */
class MyCache {
    private volatile Map<String, String> map = new HashMap<>();
//  存，写
    public void put(String key, String value) {
        System.out.println(Thread.currentThread().getName() + "写入");
        map.put(key, value);
        System.out.println(Thread.currentThread().getName() + "写入ok");
    }
//  取，读
    public void get(String key) {
        System.out.println(Thread.currentThread().getName() + "读取");
        map.get(key);
        System.out.println(Thread.currentThread().getName() + "读取ok");
    }
}
//加锁的
class MyCacheLock {
    private volatile Map<String, String> map = new HashMap<>();
    private ReadWriteLock lock = new ReentrantReadWriteLock();
    //  存，写入的时候，只希望同时只有一个线程写
    public void put(String key, String value) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写入");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入ok");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.writeLock().unlock();
        }

    }
    //  取，读
    public void get(String key) {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取");
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取ok");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.readLock().unlock();
        }

        ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程
        ExecutorService threadPool2 = Executors.newFixedThreadPool(5); //创建一个固定的线程池的大小
        ExecutorService threadPool3 = Executors.newCachedThreadPool(); //可伸缩的
    }
}

/*
执行结果：
1写入
1写入ok
2写入
2写入ok
3写入
3写入ok
4写入
4写入ok
5写入
5写入ok
3读取
3读取ok
2读取
2读取ok
1读取
1读取ok
4读取
4读取ok
5读取
5读取ok
 */